import React, { useEffect, useState } from 'react';
import { Table, Button, Modal, Form, Input, message, Popconfirm, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  addBookCategory,
  deleteBookCategory,
  listBookCategories,
  updateBookCategory,
} from '@/api/bookCategoryController';

interface BookCategory {
  id: string;
  categorycode: string;
  categorynamezh: string;
  createtime: string;
  updatetime: string;
}

const BookCategories: React.FC = () => {
  const [categories, setCategories] = useState<BookCategory[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<string | null>(null);

  const fetchCategories = async () => {
    setLoading(true);
    try {
      const response = await listBookCategories();
      if (response.data) {
        // 过滤掉 categorycode 为 'all' 的类别
        const filteredCategories = response.data.filter(
          (category) => category.categorycode !== 'all'
        );
        setCategories(filteredCategories);
      }
    } catch (error) {
      message.error('获取分类列表失败');
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  const handleAdd = () => {
    form.resetFields();
    setEditingId(null);
    setModalVisible(true);
  };

  const handleEdit = (record: BookCategory) => {
    form.setFieldsValue({
      categorycode: record.categorycode,
      categorynamezh: record.categorynamezh,
    });
    setEditingId(record.id);
    setModalVisible(true);
  };

  const handleDelete = async (id: string) => {
    try {
      await deleteBookCategory({ id });
      message.success('删除成功');
      fetchCategories();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      if (editingId) {
        // 更新
        await updateBookCategory({
          id: editingId,
          ...values,
        });
        message.success('更新成功');
      } else {
        // 新增
        await addBookCategory(values);
        message.success('添加成功');
      }
      setModalVisible(false);
      fetchCategories();
    } catch (error) {
      message.error(editingId ? '更新失败' : '添加失败');
    }
  };

  const columns: ColumnsType<BookCategory> = [
    {
      title: '分类代码',
      dataIndex: 'categorycode',
      key: 'categorycode',
    },
    {
      title: '分类名称',
      dataIndex: 'categorynamezh',
      key: 'categorynamezh',
    },
    {
      title: '创建时间',
      dataIndex: 'createtime',
      key: 'createtime',
    },
    {
      title: '更新时间',
      dataIndex: 'updatetime',
      key: 'updatetime',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个分类吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={handleAdd}>
          添加分类
        </Button>
      </div>
      <Table
        columns={columns}
        dataSource={categories}
        rowKey="id"
        loading={loading}
      />
      <Modal
        title={editingId ? '编辑分类' : '添加分类'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        okText="确认"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="categorycode"
            label="分类代码"
            rules={[{ required: true, message: '请输入分类代码' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="categorynamezh"
            label="分类名称"
            rules={[{ required: true, message: '请输入分类名称' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default BookCategories; 